#coding=utf-8
import wx

app = wx.App()
frame = wx.Frame(None,title="my calculator",size=(300,400))
bkg = wx.Panel(frame)
textprint = wx.TextCtrl(bkg,style=wx.TE_RIGHT | wx.TE_READONLY)    #设置文本框方向输入
boxsize=wx.BoxSizer(wx.VERTICAL)    #设置纵向
gridBox=wx.GridSizer(4,4,1,1)       #设置自动排版 4*4
equation = ""                       #定义一个空字符串，用于接受输入的数据
def handle(button,label):           #定义一个出来函数
    btn = "C ="
    if label not in btn:
        button.Bind(wx.EVT_BUTTON,OnAppend)
    elif label == 'C':
        button.Bind(wx.EVT_BUTTON,OnAC)
    elif label == '=':
        button.Bind(wx.EVT_BUTTON,OnEqual)

def OnAppend(event):                        #将按的数字或者运算符追加到equation中
    global  equation
    eventbutton = event.GetEventObject()    #获取对象
    label = eventbutton.GetLabel()          #得到输入的值
    equation +=label
    textprint.SetValue(equation)            #把字符串输出到文本框
def OnAC(event):                            #清空
    textprint.Clear()
    global equation
    equation = ""
def OnEqual(event):                         #计算结果
    string = textprint.GetValue()           #将文本框的结果赋值给字符串
    try:
        taget = eval(string)                #计算字符串的内容
        equation = str(taget)
        textprint.SetValue(equation)
    except :
        textprint.SetValue(u"输入错误，请重新输入！")
button_str = "7 8 9 + 4 5 6 - 1 2 3 * / 0 C =".split()  #定义一个元素列表
for i in range(len(button_str)):    #循环赋值
    label = button_str[i]
    button = wx.Button(bkg,i,label)
    handle(button,label)
    gridBox.Add(button, 0, flag=wx.EXPAND)  #附加样式
boxsize.Add(textprint, 1, flag=wx.EXPAND)   #附加样式
boxsize.Add(gridBox, 5, flag=wx.EXPAND)     #附加样式
bkg.SetSizerAndFit(boxsize)     #应用设置

frame.Show()
app.MainLoop()
